问题描述
我的代码需要一些帮助.我是Node.js的新手,遇到了很多麻烦.
I need some help with my code. I'm new at Node.js and have a lot of trouble with it.
我要做什么:
1)使用Amazon产品(ASIN)获取.txt;
1) Fetch a .txt with Amazon products (ASINs) ;
2)使用 amazon-product-api 包获取所有产品;
2) Fetch all products using the amazon-product-api package;
3)将每个产品保存在.json文件中.
3) Save each product in a .json file.
我的代码无法正常工作.我想我把这些异步的东西弄乱了-救救我吧!
My code is not working. I think I messed up with this asynchronous-synchronous stuff - help me!
var amazon = require('amazon-product-api');
var fs = require('fs');
var client = amazon.createClient({
awsId: "XXX",
awsSecret: "XXX",
awsTag: "888"
});
var array = fs.readFileSync('./test.txt').toString().split('\n');
for (var i = 1; i < array.length; i++) {
var ASIN = array[i];
return client.itemLookup({
domain: 'webservices.amazon.de',
responseGroup: 'Large',
idType: 'ASIN',
itemId: ASIN
})
.then(function(results) {
fs.writeFile(ASIN + '.json', JSON.stringify(results), function(err) {
if (err) {
console.log(err);
} else {
console.log("JSON saved");
}
})
return results;
}).catch(function(err) {
console.log(err);
});
};
推荐答案
截至2019年...
...正确的答案是对 节点中包含的本机fs
Promise模块 .升级到Node.js 10或11(主要的云提供商已支持)并执行以下操作:
As of 2019...
...the correct answer is to use async/await with the native fs
promises module included in node. Upgrade to Node.js 10 or 11 (already supported by major cloud providers) and do this:
const fs = require('fs').promises;
// This must run inside a function marked `async`:
const file = await fs.readFile('filename.txt', 'utf8');
await fs.writeFile('filename.txt', 'test');
不要使用第三方程序包,也不要编写自己的包装器,这不再是必需的.
Do not use third-party packages and do not write your own wrappers, that's not necessary anymore.
在节点11.14.0
之前,您仍然会收到警告,告知该功能是试验性的,但效果很好,是将来的方法.从11.14.0
开始,该功能不再是实验性的,并且已经可以投入生产.
Before Node 11.14.0
, you would still get a warning that this feature is experimental, but it works just fine and it's the way to go in the future. Since 11.14.0
, the feature is no longer experimental and is production-ready.
它也可以工作-但仅在未将此功能标记为实验性的Node.js版本中.
It works, too - but only in Node.js versions where this feature is not marked as experimental.
import { promises as fs } from 'fs';
(async () => {
await fs.writeFile('./test.txt', 'test', 'utf8');
})();
这篇关于fs.writeFile在一个许诺中,异步同步的东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!