Skip to content

Conversation

@egormalyutin
Copy link

Added function deasync.await, that is like await in async function, but works in sync function or global scope.

function sleepAsync(time) {
	return new Promise(function(resolve, reject) {
		setTimeout(function() {
			resolve()
		}, time)
	})
}
async function trim(str) {
	await sleepAsync(2000)
	return str.trim()
}

console.log(deasync.await(trim('       hello       ')))

@SnirBroshi
Copy link

The throw inside the catch won't really throw outside

Comment on lines +80 to +94
done = false;
result = undefined;

pr
.then(function(r) {
done = true;
return result = r;
})
.catch(function(err) {
done = true
throw err
})

deasync.loopWhile(() => { return !done });
return result;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
done = false;
result = undefined;
pr
.then(function(r) {
done = true;
return result = r;
})
.catch(function(err) {
done = true
throw err
})
deasync.loopWhile(() => { return !done });
return result;
done = false;
result = undefined;
error = undefined;
pr
.then(function(r) {
done = true;
result = r;
})
.catch(function(err) {
done = true;
error = err;
})
deasync.loopWhile(function() { return !done; });
if (error) throw error;
return result;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about errors what are falsy? for example Promise.reject(0) or Promise.reject(undefined).
This still would no throw an exception

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@NotWearingPants I forgot that those rejections are technically possible. Indeed to cover that it would be better to use a didThrow variable instead.

@aminya aminya mentioned this pull request Dec 16, 2020
@loynoir
Copy link

loynoir commented Nov 10, 2021

deasync.await = p => deasync((cb)=>p.then(x=>cb(null,x),e=>cb(e,null)))()
> deasync.await(import('some-esm-module'))
[Module: null prototype] {
...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants