You do not need to explicitly create a new promise. There is an easier way.
This example is contrived because it will never fail, but the point is that you do not need to create a promise and you do not need to return a solution (val).
function syncFunction() { var j = "hi" if(j){ return j; } return new Error('i am an error'); }
This will work:
asyncFunction() .then(syncFunction);
But if you did it the other way around:
syncFunction() .then(asyncFunction);
You need to define your synchronization as:
function syncFunction() { var j = "hi" return new Promise((resolve, reject) => { if(j){ return resolve(j); } return reject('error'); }) }
Edit: To prove to everyone who doesn't believe you, let this guy shoot locally on your computer. It is proven that you have many options for you. :)
var Promise = require('bluebird'); function b(h) { if(h){ return h; } return Promise.resolve('hello from b'); } function a(z) { return new Promise((resolve, reject)=> { if(z){return resolve(z)}; return resolve('hello from a'); }) } a().then(b).then(x => console.log(x)).catch(e => console.log(e)); b().then(a).then(x => console.log(x)).catch(e => console.log(e));
source share