javascript promise wait for function to finish code example
Example 1: javascript synchronous wait
function delay(n) {
n = n || 2000;
return new Promise(done => {
setTimeout(() => {
done();
}, n);
});
}
Example 2: wait for ajax to finish
function functABC() {
return new Promise(function(resolve, reject) {
$.ajax({
url: 'myPage.php',
data: {id: id},
success: function(data) {
resolve(data)
},
error: function(err) {
reject(err)
}
});
});
}
functABC().then(function(data) {
console.log(data)
}).catch(function(err) {
console.log(err)
})
Example 3: how to wait for a function to finish in javascript
function doFirst() {
return new Promise(function(resolve, reject) {
if (){
return reject(value);
}
resolve(value);
});
});
}
async function doSecond() {
var outputValue = await doFirst();
console.log(outputValue);
}