Reputation: 85
How can I wait until the function a is complete, but is not working as I expected.
Here is my code:
var start = Date.now();
function a() {
setTimeout(function(){ console.log(Date.now() - start); }, 500);
for(var i=0; i<100; i++) {
console.log(i);
//
}
}
const main = async () => {
await a();
console.log("Done");
};
main().catch(console.error);
Upvotes: 2
Views: 787
Reputation: 2081
you can use q module for make promise also:
var q = require('q')
var start = Date.now();
function a() {
let defer = q.defer()
setTimeout(function(){ console.log(Date.now() - start); defer.resolve();}, 500)
for(var i=0; i<100; i++) {
console.log(i);
}
return defer.promise;
}
const main = async () => {
await a();
console.log("Done");
};
main().catch(console.error);
Upvotes: 0
Reputation: 3386
You have to return promise when you call await. The await operator is used to wait for a Promise. It can only be used inside an async function. Check here for more details:
var start = Date.now();
function a() {
return new Promise(function(resolve, reject) {
setTimeout(function(){ console.log(Date.now() - start); resolve()}, 500);
for(var i=0; i<100; i++) {
console.log(i);
//
}
})
}
const main = async () => {
await a();
console.log("Done");
};
main().catch(console.error);
Upvotes: 1
Reputation: 1761
var start = Date.now();
function a() {
return new Promise((resolve, reject)=> {
setTimeout(function(){ console.log(Date.now() - start); resolve() }, 500);
for(var i=0; i<100; i++) {
console.log(i);
//
}
});
}
const main = async () => {
await a();
console.log("Done");
};
main().catch(console.error);
Upvotes: 0