简体   繁体   中英

How do I use a nodjes promise value in another function

I'm having two functions in nodejs. One looks like this

function checkAdd (
  address /* : string | void */
) /* :Promise<Object[]> */ {

  var convertToLowerCase = address.toLowerCase()

    return Promise.resolve()

    .then(() => {
      var allMatch = addressesAsJson.filter((record) => record.address === convertToLowerCase)

 });

}

There's another function like this

function saveNewAd(
  address /* :?string | void */, cb
) /* :Promise<string> */ {

  return new Promise((resolve, reject)=> {


    var checkAddress = checkAddressAvailable(address)

    var addressAvailableResult = checkAddressAvailable(address)

    var seperatedAddress = address.split(',') 
    var firstAddLine  = capitalFirstLetter(seperatedAddress[0])
    var secondAddLine = seperatedAddress[1].toUpperCase()
    var thirdAddLine =  seperatedAddress[2].toUpperCase()

    var displayAddress = firstAddLine + ',' + secondAddLine + ',' + thirdAddLine

    addressesAsJson.push({"address": address , "display" : displayAddress})    
    fs.writeFile(jsonListPath, JSON.stringify(addressesAsJson), (err) => {
      if (err) reject(err)
      resolve("New address is saved")

    })


  });
}

Inside saveNewAd, I want to check the allMatch length and if it's more than 0, I need to execute the function body of saveNewAd. But it's not working. This is what I tried. Please help me to solve this issue

function saveNewAd(
  address /* :?string | void */, cb
) /* :Promise<string> */ {

  return new Promise((resolve, reject)=> {

    var results = checkAdd(address)

    if(results.length>0){

   /*same function body as above method*/

    })
    }else{
    console.log("Error")
    }

  });
}

You have to make use of chaining, ie first finding out allMatch asynchronously and then passing this value down through .then() to saveNewAd function as an argument. Note that the .then() function actually returns a new promise, different from the original.

function checkAdd (
  address /* : string | void */
) /* :Promise<Object[]> */ {

  return new Promise((resolve, reject)=> {
    var convertToLowerCase = address.toLowerCase();

    var allMatch = addressesAsJson.filter((record) => record.address);

    resolve(allMatch);
  }
}

checkAdd()
.then((allMatch) => {
   saveNewAd(address, cb, allMatch); // now you can use allMatch as an argument in this function
}
===

MDN docs: Using Promises .

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