简体   繁体   中英

Promisify a JavaScript callback function

I've been reading everything I can about async/await and Promises, but I can't quite get it to work. I keep getting 'Promise ' and when it's fulfilled I receive 'Undefined'.

I think I've spent about two days on this. I'm not sure what's wrong. Here's the un-promisified version.

  const getCoords = (address) => {
    geocoder.addressSearch(address, (result) => {
        return result;
      }
    );
  };

And here is my attempt at the promised code:

  const getCoords = async (address) => {
     await geocoder.addressSearch(address, async (result) => {
        return result;
  }
);

};

I'm just trying to return the result. If anyone could steer me in the right direction it would be really appreciated.

Both of your examples are incorrect

using continuation-passing style

In this style, the continuation ("callback") ignores any return values as this function is run asynchronously from the main call -

 const geocoder = { addressSearch: (address, callback) => setTimeout(callback, 1000, { coords: [12.345, 67.890] }) } const getCoords = (address, callback) => geocoder.addressSearch(address, result => callback(result.coords) ) getCoords("foobar", console.log) // [ 12.345, 67.89]

[ 12.345, 67.89]

using promises

In this style you do not specify a continuation. Instead a Promise is returned which represents the value of a future computation. You can await a promise in an async function in order to retrieve the result, or chain a .then handler -

 const geocoder = { addressSearch: (address, callback) => setTimeout(callback, 1000, { coords: [12.345, 67.890] }) } const getCoords = (address) => new Promise(resolve => geocoder.addressSearch(address, result => resolve(result.coords) ) ) async function main() { const coords = await getCoords("foobar") console.log(coords) return "done" } main().then(console.log, console.error)

[ 12.345, 67.89]
"done"

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