gpt4 book ai didi

javascript - 使用 ES6 Promise 进行递归的好方法?

转载 作者:行者123 更新时间:2023-11-27 23:56:16 25 4
gpt4 key购买 nike

这是我得到的:

function nextAvailableFilename(path) {
return new Promise(function (resolve, reject) {
FileSystem.exists(path, function (exists) {
if (!exists) return resolve(path);

var ext = Path.extname(path);
var pathWithoutExt = path.slice(0, -ext.length);

var match = /\d+$/.exec(pathWithoutExt);
var number = 1;

if (match) {
number = parseInt(match[0]);
pathWithoutExt = pathWithoutExt.slice(0, -match[0].length);
}

++number;

nextAvailableFilename(pathWithoutExt + number + ext).then(function () {
return resolve.apply(undefined, arguments);
}, function () {
return reject.apply(undefined, arguments);
});
});
});
}

但我不喜欢最后的那个 block ——有没有一种方法可以用堆栈中的下一个 promise “替换”当前的 promise ,而不是像我在这里所做的那样让一个 promise 解决下一个 promise ?

最佳答案

这是一个使用 promise 链接和文件创建来避免竞争条件的版本。我使用了 bluebird Promise 库,因此我可以将 Promise 与 fs 库一起使用,以简化代码和错误处理:

var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
var path = require('path');

// Creates next available xxx/yyy/foo4.txt numeric sequenced file that does
// not yet exist. Returns the new filename in the promise
// Calling this function will create a new empty file.
function nextAvailableFilename(filename) {
return fs.openAsync(filename, "wx+").then(function(fd) {
return fs.closeAsync(fd).then(function() {
return filename;
});
}, function(err) {
if (err.code !== 'EEXIST') {
// unexpected file system error
// to avoid possible looping forever, we must bail
// and cause rejected promise to be returned
throw err;
}
// Previous file exists so reate a new filename
// xxx/yyy/foo4.txt becomes xxx/yyy/foo5.txt
var ext = path.extname(filename);
var filenameWithoutExt = filename.slice(0, -ext.length);
var number = 0;
var match = filenameWithoutExt.match(/\d+$/);
if (match) {
number = parseInt(match[0], 10);
filenameWithoutExt = filenameWithoutExt.slice(0, -match[0].length);
}
++number;
// call this function again, returning the promise
// which will cause it to chain onto previous promise
return nextAvailableFilename(filenameWithoutExt + number + ext);
});
}

关于javascript - 使用 ES6 Promise 进行递归的好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32275719/

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