简体   繁体   中英

Resolve Promise After Executing Single Line Of Code

I have a sequence of events I'm trying to align, but I don't understand how to resolve a promise after a single line of asynchronous code. In this case, I'm making an API call which resolves to an array of objects. I'm then using Object.assign() to convert the array of objects into an object of objects. Once completed, I then want to call a function which does something with that new object of objects. The conversion process takes some time, and I'm not sure how to postpone my function call until after the object has been converted. My non-functioning code is given below.

this.queryCodes().then(() => {
  new Promise((resolve) => {
    resolve(() => {
      // This code isn't executing.
      this.floorCodesLookup = Object.assign({}, ...this.floorCodes);
    });
  }).then((data) => {
    this.resolveCodesToDescriptions();
  });
});

resolve should be given the result of your asynchronous operation, not the code to execute. The code you want to execute shouldn't go in the resolve argument, but instead in the callback you give to the promise constructor. So for your snippet:

this.queryCodes().then(() => {
  return new Promise((resolve) => {
    // Put the code you want to execute here...
    // Call resolve when your work is done, and pass it the result if there is one.
    resolve(/* maybe result here */);
  }).then((data) => {
    this.resolveCodesToDescriptions();
  });
});

It's also worth noting that you don't need to use a promise constructor since you're already chaining off a promise to begin with. You could just:

this.queryCodes().then(() => {
  // Do additional work here...
  this.floorCodesLookup = Object.assign({}, ...this.floorCodes);
  return this.resolveCodesToDescriptions();
});

resolve() doesn't take a callback as an argument. It takes the resolved value as an argument. Not sure where you got the callback notion from. That's why the callback is never called because that's not a supported feature of resolve() .

Manually creating a promise inside a .then() handler is likely not needed and is probably an anti-pattern . You don't show enough of the real code here to understand what is going on, but this is likely way more complicated than it needs to be. From the code you show, I think you can just do this:

this.queryCodes().then(() => {
   this.floorCodesLookup = Object.assign({}, ...this.floorCodes);
   this.resolveCodesToDescriptions();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM