How to make promises execute in order?

61 Views Asked by At

First, the project has a feature to monitor data changes.

Then, I want to set new value to a data and then get its value again. Before setting it, I need to know its old value to trigger data changes (get old value -> set new value, get new value).

But the getter and setter are both promises, so the second getter will get old value (the apis comes from third party).

The following is the minimal code to reproduce:

let promise = ''

function A() {
  return new Promise((resolve) => {
    resolve(promise)
  })
}

function callbackA(res) {
  console.log("callbackA:", res)
  
  return new Promise(resolve => {
    promise = 'A'
    resolve()
  })
}

function B() {
  return new Promise((resolve) => {
    resolve(promise)
  })
}

function callbackB(res) {
  console.log("callbackB:", res)
}

function C() {
  promise = 'C'
  return promise
}

function callbackC(res) {
  console.log("callbackC:", res)
}

function promiseThen(maybePromise, callback) {
}

promiseThen(A, callbackA)
promiseThen(B, callbackB)
promiseThen(C, callbackC)

The function promiseThen accepts two parameters: maybePromise, which may be a promise or a regular function, and callback, which receives their results to operate on them.

I want the promise to be executed first, completing all of its then functions, and then proceed to the next promise. So the result of the above code should be:

callbackC: C
callbackA: C
callbackB: A

I don't think everyone likes promisify. I just want to unpromisify.

1

There are 1 best solutions below

1
digitalniweb On

Why don't you just use await?

try{
    let a = await callbackA(); 
    let b = await callbackB(a); 
    let c = await callbackC(b);
} catch(err){}