我在nodejs中有两个功能。一个看起来像这样
function checkAdd (
address /* : string | void */
) /* :Promise<Object[]> */ {
var convertToLowerCase = address.toLowerCase()
return Promise.resolve()
.then(() => {
var allMatch = addressesAsJson.filter((record) => record.address === convertToLowerCase)
});
}
还有另外一个这样的功能
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")
})
});
}
在saveNewAd中,我想检查allMatch长度,如果它超过0,我需要执行saveNewAd的函数体。但它不起作用。这是我试过的。请帮我解决这个问题
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")
}
});
}
答案 0 :(得分:0)
您必须使用链接,即首先异步查找allMatch
,然后将此值通过.then()
传递给saveNewAd
函数作为参数。请注意,.then()
函数实际上返回了一个与原始承诺不同的新承诺。
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文档:Using Promises。