gpt4 book ai didi

javascript - 使用自定义方法扩展 $.Deferred.pipe() ?

转载 作者:行者123 更新时间:2023-12-01 01:50:22 25 4
gpt4 key购买 nike

我想使用自定义方法扩展 $.Deferred.pipe,这样我就可以稍微缩短我的延迟链。

我目前拥有的代码是这个

getDeferredFileEntry() 
//returns a ($.Deferred) promise to resolve with a FileEntry object
.pipe(function(entry){
//returns a promise to resolve with an object
//containing the contents of the file as text
//and a reference to the file's FileEntry
var def = $.Deferred();
entry.getDeferredText()
.done(function(fileText){
def.resolve({text:fileText, fileEntry:entry});
});
return def.promise();
)}
.done(function(response){
var text = response.text;
var fileEntry = response.fileEntry;

console.log(text);
//do something with the text
console.log(fileEntry);
//do something else with the file entry after finished reading from it
//e.g. deleting with something like fileEntry.remove();
});

我想将其缩短为

getDeferredFileEntry()
.read(
//uses the FileEntry object resolved by getDeferredFileEntry
//to call an asynchronous fileEntry.read() *in the background*
//the contents are then passed to the callback taken from below
//returns promise to resolve with the fileEntry object for chaining
function callback(text){
//do something with the text
console.log(text);
}
)
.remove(
function(fileEntry){
//library call to remove fileEntry that read() promised
}
)

我正在努力解决如何将从 getDeferredFileEntry() 解析的 FileEntry 对象传递到后台的自定义 read() 。任何建议将不胜感激

最佳答案

为什么不简单地创建一些辅助方法来抽象管道逻辑?

function getFileEntry() {
// Returns a promise resolved when your file entry is available
}

function getFileContents( entryPromise ) {
return entryPromise.pipe(function( entry ) {
return readFileEntry( entry );
});
}

function readFileEntry( entry ) {
var dfr = $.Deferred();

// do whatever you have to do to read the file
// then call dfr.resolve( fileContents );

return dfr.promise();
}

function removeFileEntry( entry ) {
var dfr = $.Deferred();

// do whatever you have to do to remove the file
// then call dfr.resolve();

return dfr.promise();
}

使用这些方法,您的代码最终应如下所示:

var fileEntry = getFileEntry();

readFileEntry( fileEntry ).then(function(contents) {
// Do something with your file contents
removeFileEntry( fileEntry );
});

关于javascript - 使用自定义方法扩展 $.Deferred.pipe() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12466776/

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