我是Angularjs的新手,我正在学习本教程:http://mherman.org/blog/2015/07/02/handling-user-authentication-with-the-mean-stack/#.WE70iubhCM8 .但是我不明白何时使用$ q.defer().例如,在下面的Angularjs代码中,为什么要使用$ q.defer():
function login(username, password) {
// create a new instance of deferred
var deferred = $q.defer();
// send a post request to the server
$http.post('/user/login',
{username: username, password: password})
// handle success
.success(function (data, status) {
if(status === 200 && data.status){
user = true;
deferred.resolve();
} else {
user = false;
deferred.reject();
}
})
// handle error
.error(function (data) {
user = false;
deferred.reject();
});
Run Code Online (Sandbox Code Playgroud)
服务器端代码是:
router.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) …Run Code Online (Sandbox Code Playgroud) 我有一个函数数组,其中每个函数promise从ajax调用返回.
var promises = [];
if (form.$valid) {
Object.keys($scope.Model.Data.FormFiles).forEach(function (key) {
var file = $scope.Model.Data.FormFiles[key];
function uploadFile(){
var deferred = $q.defer();
var upload = Upload.upload({
url: "/api/ir/funnelApi/UploadFile",
data: { file: file }
});
upload.then(function (response) {
// do something
deferred.resolve(response.statusText);
}, function (error) {
deferred.reject(error.data);
}, function (evt) {
});
return deferred.promise;
}
promises.push(uploadFile);
});
}
Run Code Online (Sandbox Code Playgroud)
我想要做的是,如果所有文件都已成功上传,那么做一些事情.
$q.all(promises).then(function (responses) {
// do something
}, function (errors) {
// if any of the file upload fails, it should come …Run Code Online (Sandbox Code Playgroud) 我并不是真正的承诺忍者,我知道我做错了。但是,我找不到与我遇到的问题相关的特定/类似问题。
问题:我对 IndexedDB 使用异步的 Dexie.js 包装器。我有一个全局数据库,它通向其他一些 dexie 数据库。
function handleDatabases() {
var result = [];
db.jobs.orderBy('title').filter(function(job) {
return job.someBooleanCondition;
}).each(function(job, cursor) {
let jobDetails = new Dexie(job.correspondingDB);
jobDetails.version(1).stores({
details: 'key,value1,value2'
});
jobDetails.details.get(someKey).then(function(detail) {
result.push({job: job, detail: detail});
})
}).catch(function(error) {
console.log(error);
});
handleResult(result);
}
Run Code Online (Sandbox Code Playgroud)
我已经用一种可能奇怪的形式重写了它,但最终目标是我可以使用数组result来处理一些更新。但是,由于它是异步的,因此它始终为空,直到您在控制台中检查它,它永远不会为空。我怎样才能将其重写为同步?
我正在努力扩展我的知识(初学者阶段).基本上,我想使用promises向我的用户写新的电子邮件.我在我的游戏项目中有一些代码库,但我的功能并没有停止.这是应该写入数据库的函数:
changeEmailAddress(user, newEmail) {
new Promise((resolve, reject) => {
user.setEmail(newEmail);
userRepository.saveUser(user).then(() => {
return resolve();
}).catch(e => {
return reject(e);
});
}
);
}
Run Code Online (Sandbox Code Playgroud)
如果我没有弄错的话,我应该如何使用它:
changeEmailAddress(user, "hello@there.com").then(function () {
//it never comes in here :(
})
Run Code Online (Sandbox Code Playgroud)
我有类似的功能在用户工作,但我的功能是没有进入'然后'
我是承诺的新手,我使用蓝鸟文档从异步代码中获取数据
我尝试的是以下内容:
错误是:
getToken.then不是一个功能
我怎么能避免呢?
这个文件是connection.js
return connection.getToken.then(function(connToken){
console.log(connToken);
}).catch({
})
Run Code Online (Sandbox Code Playgroud)
这是moduleB中的getToken代码
const request = require("request-promise");
const Promise = require("bluebird");
module.exports = {
getToken: function () {
return new Promise((resolve, reject) => {
let options = {
method: 'POST',
url: 'https://authentication.arc.com/oauth/token',
headers: {
grant_type: 'client_credentials',
authorization: 'Q0MDdmMCFiMTc0fGNvlQVRDWThDNDFsdkhibGNTbz0=',
accept: 'application/json;charset=utf-8',
'content-type': 'application/x-www-form-urlencoded'
},
form: {
grant_type: 'client_credentials',
token_format: 'opaque&response_type=token'
}
};
request(options)
.then(function (body) {
return body;
})
.catch(function (err) {
return err;
});
})
}
}
Run Code Online (Sandbox Code Playgroud) 我有以下promise函数,该函数使用fetch从API获取数据:
const getContacts = token =>
new Promise((resolve, reject) => {
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then((data) => {
resolve(data);
})
.catch(err => reject(err));
});
Run Code Online (Sandbox Code Playgroud)
然后在另一个文件中调用此函数:
getContacts(token)
.then((data) => {
const contacts = data.data;
console.log(contacts);
})
.catch(err => console.error(err));
Run Code Online (Sandbox Code Playgroud)
当从API返回的数据量较大时,将对其进行分页。响应中包含一个链接,需要获取该链接才能获取下一页。我希望我的代码首先遍历所有页面并收集所有数据,然后解决承诺。当执行到达该const contacts = data.data行时,它应该具有每个页面的数据(当前它仅返回第一页)。
实现这一目标的最佳方法是什么?
编辑:
我尝试在getContacts函数中进行递归。这样,我可以遍历所有页面并在一个对象中获取所有数据,但是我不知道什么是将其解析回代码(最初称为函数)的正确方法。下面的代码无法正确解析。
const getContacts = (token, allData, startFrom) =>
new Promise((resolve, reject) => {
if (startFrom) {
url = `${url}?${startFrom}`; // the api returns a set …Run Code Online (Sandbox Code Playgroud) 我有以下代码用于处理Magento 2 REST API。
return new Promise((resolve, reject) => {
fetch(uri, { method, headers, body: JSON.stringify(data) })
.then(response => {
return response.json();
})
.then(responseData => {
resolve(responseData);
})
.catch(error => {
reject(error);
});
});
Run Code Online (Sandbox Code Playgroud)
我想添加响应状态检查,所以我已经开始像这样
return new Promise((resolve, reject) => {
fetch(uri, { method, headers, body: JSON.stringify(data) })
.then(response => {
return {
data: response.json(),
ok: response.ok,
status: response.statusText
};
})
.then(responseResult => {
if (responseResult.ok) {
resolve(responseResult.data);
} else {
const error = responseResult.status || responseResult.data.message;
reject(error);
}
}) …Run Code Online (Sandbox Code Playgroud) 我在我的业余爱好节点项目中遇到这个问题.我有一个函数(processDataSet)正在处理数据数组(inputArray)并返回一个promise.该函数使用for循环遍历输入数组并saveObjectData在每一轮调用函数.此保存功能处理单个数据条目并返回承诺.
似乎如果saveObjectData函数失败,processDataSet函数捕获返回拒绝,但它自己reject似乎没有在for循环中正确调用.我认为这是一个时间问题,我不明白.查看代码下方的输出打印结果.
function processDataSet(inputArray, scriptConfig) {
var contentType = scriptConfig.contentType;
return new Promise(function(resolve, reject) {
if(!Array.isArray(inputArray)) {
return reject(new Error("Input data is not an array. Cannot process."));
}
if(!scriptConfig) {
return reject(new Error("Invalid scriptConfig"));
}
if(!typeof contentType === "string" && !contentType instanceof String) {
return reject(new Error("Invalid contentType for the data set. The parameter should be a string."));
}
console.log("Post processing data for the script " + scriptConfig.name …Run Code Online (Sandbox Code Playgroud) 我正在尝试删除一些文件,然后显示一条消息。
预期产出
File deleted
Folder Cleared!!!
Run Code Online (Sandbox Code Playgroud)
实际产量
Folder Cleared!!!
File deleted
Run Code Online (Sandbox Code Playgroud)
当前的代码是:
File deleted
Folder Cleared!!!
Run Code Online (Sandbox Code Playgroud)
你可以帮我吗?
我是 Node.js 的新手,能够使用 promise 一一运行这些命令:
let promise1 = new Promise(function (resolve, reject) {
sftp.connect({
host: host,
username: user,
privateKey: fs.readFileSync(pemfile)
}).then(() => {
return sftp.get(remotePath, fs.createWriteStream(localPath)); //This writes from a remote file to a local file
}).then(() => {
sftp.end();
resolve();
})
.catch(err => {
console.error(err.message);
reject(err);
});
});
await promise1;
let promise2 = new Promise(function (resolve, reject) {
fs.readFile(localPath, 'utf8', function (err, data) {
if (err) {
reject(err);
}
resolve(data);
});
});
let data = await promise2;
Run Code Online (Sandbox Code Playgroud)
这有效,但我知道这不是最好的方法。有一个更好的方法吗?
javascript ×9
promise ×7
node.js ×4
angularjs ×2
ajax ×1
async-await ×1
asynchronous ×1
bluebird ×1
dexie ×1
es6-promise ×1
fetch ×1
file ×1
mean-stack ×1
q ×1