Javascript 如何通过承诺使这段代码异步?
任何胶水请不要给出设置超时的示例。 我的主管说,如果then()没有返回任何新的承诺,那么就没有必要有更多的then()声明。我不能完全得到它,我已经研究过探索ES6,但没有很好的例子说明我的情况Javascript 如何通过承诺使这段代码异步?,javascript,node.js,ecmascript-6,es6-promise,Javascript,Node.js,Ecmascript 6,Es6 Promise,任何胶水请不要给出设置超时的示例。 我的主管说,如果then()没有返回任何新的承诺,那么就没有必要有更多的then()声明。我不能完全得到它,我已经研究过探索ES6,但没有很好的例子说明我的情况 let readData=新承诺(函数(解析、拒绝){ fs.readFile('/home/geek/Desktop/activitylogs.csv','utf8',(err,data)=>{ 如果(错误) 拒绝(); 解析(数据); }); }); 读取数据 。然后((数据)=>{ 银行日志=
let readData=新承诺(函数(解析、拒绝){
fs.readFile('/home/geek/Desktop/activitylogs.csv','utf8',(err,data)=>{
如果(错误)
拒绝();
解析(数据);
});
});
读取数据
。然后((数据)=>{
银行日志=拆分字符串(数据“;”)
})
.然后(()=>{
对于(让索引=2;索引 .catch((err)=>console.log('发生错误:'+err))代码>从代码片段中,您实现了承诺链,其中解析一个承诺将初始化并返回新的承诺
比如:
let readData = new Promise(/* ... */);
readData.then((data) => {
let promise2 = new Promise(/* ... */);
return promise2;
}).then(() => {
// ...
})
.catch((err) => console.log('Error happened : ' + err));
但是,在解析readData
之后,您只编写了简单的逻辑,没有新的承诺:bankLogs=splitString(data,“;”)
因此,它应该是:
let readData = new Promise(function (resolve, reject) {
fs.readFile('/home/geek/Desktop/activity-logs.csv', 'utf8', (err, data) => {
if (err)
reject();
resolve(data);
});
});
readData.then((data) => {
var bankLogs = splitString(data, ';')
for (let index = 2; index < bankLogs.length; index += 5) {
objectOfUsers[bankLogs[index]] = {}
temporarySymbols.push(bankLogs[index].concat(bankLogs[index + 1]));
}
Object.keys(objectOfUsers).forEach(function (element) {
objectKeys.push(element)
});
for (let index = 0; index < objectKeys.length; index++)
createObject(index);
console.log(objectOfUsers)
})
.catch((err) => console.log('Error happened : ' + err));
那么你的问题是什么?代码的哪一部分是问题?看起来你已经使用了promise,它是异步的。首先是。然后((数据)=>{return splitString(数据,;)})。然后((银行日志)=>{
。之后,你的代码让我太困惑了。请解释你想做什么(包括为什么你只取第五个索引,例如)还包括一些sampledata和您正在使用的函数。拥有更多Than并不是不必要的。下一步然后即使在上一步然后中没有返回也可以工作。我曾多次使用then()语句,但他说没有必要,如果then()语句返回一个新的承诺。我无法得到它。此外,他说您应该在then()语句中使用局部变量而不是全局变量。这段代码promise.resolve()。然后(function(){console.log('promise1');})。然后(function(){console.log('promise2');})
你会理解的。也许你的主管是错的。我不只是在一个承诺中使用银行日志,我在代码的其他部分使用了银行日志。因此,我将其声明为全局变量,但主管说,与其使其成为全局变量,不如使用局部变量,并通过承诺链实现。但我不能举任何例子,(事实上,所有的例子都包含SETTIMEOUT,但它与mmy的情况不同。)顺便说一句,非常感谢您关心我。
'use strict';
var fs = require('fs');
let readData = new Promise(function (resolve, reject) {
fs.readFile('/Users/maxim/Appsflyer/projects/ZEVEL/file1.txt', 'utf8', (err, data) => {
if (err)
reject();
var obj = {
data: data,
bankLogs: {} // in 1st Promise initialize bankLogs
};
resolve(obj);
});
});
// 2nd dummy Promise
let newReadData = new Promise(function (resolve, reject) {
fs.readFile('/Users/maxim/Appsflyer/projects/ZEVEL/file2.txt', 'utf8', (err, data) => {
if (err)
reject();
resolve(data);
});
});
readData.then((obj1) => {
obj1.bankLogs.value = "someValue";
return newReadData.then(function(data2){
obj1.data2 = data2;
return obj1;
});
}).then((dataTotal) => {
console.log(dataTotal);
})
.catch((err) => console.log('Error happened : ' + err));