gpt4 book ai didi

javascript - 如何将自定义变量传递到 Promise 中,以跟踪用于调用函数的内容?

转载 作者:行者123 更新时间:2023-12-03 04:02:29 25 4
gpt4 key购买 nike

我有一组要进行地理编码的地址列表。我的问题是我想在 promise 的每个响应中包含一个自定义属性“originalPlaceName”,以便我可以跟踪我最初传入的内容?这可能吗?

var Promise = require("bluebird");
var geocoder = Promise.promisifyAll(require('geocoder'));
var fs = require('fs');
var async = require('async');
var parse = require('csv-parse/lib/sync');
var inputFile = './myaddresses.txt'
var file = fs.readFileSync(inputFile, "utf8");

var records = parse(file, {columns: true});
var promises = [];
for(var i = 0; i < records.length; i++) {
var placeName = records[i]['Place Name'];
promises.push(geocoder.geocodeAsync(placeName));
}

Promises.all(promises).then(function(result) {
result.forEach(function(geocodeResponse) {
// how do I access the original "placeName" variable in here?
})
}

最佳答案

首先,我建议使用数组映射函数而不是 forEach 来推送数组类型的东西 - 这会稍微简化代码

var Promise = require("bluebird");
var geocoder = Promise.promisifyAll(require('geocoder'));
var fs = require('fs');
var async = require('async');
var parse = require('csv-parse/lib/sync');
var inputFile = './myaddresses.txt'
var file = fs.readFileSync(inputFile, "utf8");
var records = parse(file, {columns: true});

// changes start here

Promises.all(records.map(record => {
let placeName = record['Place Name'];
return geocoder.geocodeAsync(placeName)
// add the placeName to the result of geocodeAsync
.then(result => Object.assign(result, {placeName}));
}))
.then(results => {
results.forEach(geocodeResponse => {
// geocodeResponse is each result with the added property:
// placeName, which is geocodeResponse.placeName
})
})

这将导致仅将 placeName 属性添加到由 geocodeAsync 解析的对象

或者您可以执行以下操作

Promises.all(records.map(record => {
let placeName = record['Place Name'];
return geocoder.geocodeAsync(placeName)
// add the placeName to the result of geocodeAsync
.then(result => ({result, placeName}));
}))
.then(results => {
results.forEach(geocodeResponse => {
// original geocode result is at geocodeResponse.result
// original placeName is at geocodeResponse.placeName
})
})

现在,结果数组中的每个结果将是

{
result: result of geocodeAsync,
placeName: original place name
}

注意:Promise.all(...) 代码可以进一步“简化”为

Promises.all(records.map(({'Place Name': placeName}) => geocoder.geocodeAsync(placeName).then(result => Object.assign(result, {placeName}))))

Promises.all(records.map(({'Place Name': placeName}) => geocoder.geocodeAsync(placeName).then(result => ({result, placeName}))))

分别

关于javascript - 如何将自定义变量传递到 Promise 中,以跟踪用于调用函数的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44666123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com