我想重复执行一个操作,每次操作之间的超时时间增加,直到成功或经过一定的时间.我如何用Q中的承诺来构建它?
我正在使用Puppeteer尝试在所有图像加载后尝试截取网站,但无法使其工作.
这是我到目前为止的代码,我使用https://www.digg.com作为示例网站:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://www.digg.com/');
await page.setViewport({width: 1640, height: 800});
await page.evaluate(() => {
return Promise.resolve(window.scrollTo(0,document.body.scrollHeight));
});
await page.waitFor(1000);
await page.evaluate(() => {
var images = document.querySelectorAll('img');
function preLoad() {
var promises = [];
function loadImage(img) {
return new Promise(function(resolve,reject) {
if (img.complete) {
resolve(img)
}
img.onload = function() {
resolve(img);
};
img.onerror = function(e) {
resolve(img);
};
}) …Run Code Online (Sandbox Code Playgroud) 我正试图通过Node.js的async/await功能来使用Mongoose promises.当我的函数printEmployees被调用时,我想保存由orderEmployees函数查询的员工列表.同时,console.log语句内部orderEmployees返回预期的查询,返回的console.log内部,表明我没有正确地返回promise.printEmployeesundefined
我很容易接受承诺,以至于我没有正确理解范式......任何帮助都非常感激.
printEmployees: async(company) => {
var employees = await self.orderEmployees(company);
// SECOND CONSOLE.LOG
console.log(employees);
},
orderEmployees: (companyID) => {
User.find({company:companyID})
.exec()
.then((employees) => {
// FIRST CONSOLE.LOG
console.log(employees);
return employees;
})
.catch((err) => {
return 'error occured';
});
},
Run Code Online (Sandbox Code Playgroud) 我一直在为我自己使用的小型2D游戏库工作,我遇到了一些问题.库中有一个名为loadGame的特定函数,它将依赖信息作为输入(资源文件和要执行的脚本列表).这是一个例子.
loadGame({
"root" : "/source/folder/for/game/",
"resources" : {
"soundEffect" : "audio/sound.mp3",
"someImage" : "images/something.png",
"someJSON" : "json/map.json"
},
"scripts" : [
"js/helperScript.js",
"js/mainScript.js"
]
})
Run Code Online (Sandbox Code Playgroud)
资源中的每个项目都有一个密钥,游戏使用该密钥来访问该特定资源.loadGame函数将资源转换为promises对象.
问题是它试图使用Promises.all来检查它们何时准备就绪,但是Promise.all只接受迭代作为输入 - 所以像我所拥有的对象是不可能的.
所以我尝试将对象转换为数组,这很有效,除了每个资源只是数组中的一个元素,并且没有用于标识它们的键.
这是loadGame的代码:
var loadGame = function (game) {
return new Promise(function (fulfill, reject) {
// the root folder for the game
var root = game.root || '';
// these are the types of files that can be loaded
// getImage, getAudio, and getJSON are defined elsewhere in my code - they …Run Code Online (Sandbox Code Playgroud) 我有一个返回promise的库中的函数.我需要多次运行此函数,但每次迭代必须等到上一个任务完成.
我的假设是我能做到这一点:
promiseReturner(1)
.then(promiseReturner(2)
.then(promiseReturner(3)
.then(...)
Run Code Online (Sandbox Code Playgroud)
可以使用循环简化:
var p = Promise.resolve();
for (var i=1; i<=10; i++) {
p = p.then(promiseReturner(i));
}
Run Code Online (Sandbox Code Playgroud)
但是,当我这样做时,链中的每个承诺都会同时执行,而不是一个接一个地执行,.then()似乎意味着.显然,我遗漏了一些关于承诺的基本信息 - 但在阅读了几篇教程和博客文章后,我仍然迷失了.
我正在尝试使用promises实现while循环.
这里概述的方法似乎有效. http://blog.victorquinn.com/javascript-promise-while-loop 它使用这样的函数
var Promise = require('bluebird');
var promiseWhile = function(condition, action) {
var resolver = Promise.defer();
var loop = function() {
if (!condition()) return resolver.resolve();
return Promise.cast(action())
.then(loop)
.catch(resolver.reject);
};
process.nextTick(loop);
return resolver.promise;
};
Run Code Online (Sandbox Code Playgroud)
这似乎使用反模式和弃用的方法,如强制转换和延迟.
有谁知道更好或更现代的方法来实现这一目标?
谢谢
如何在使用promises时正确转义取消按钮而不会抛出错误?我的代码会抛出一个带有必填复选框的警报确认.代码应该对用户执行,但它会在控制台窗口中引发错误:
未被捕(承诺)取消
//validation logic all passes...Now proceed to...
else
{
//determine and parse Discounts
var myLookup = document.getElementsByName("myLookup")[0].value;
$.post( "findthem.php", {myLookup: myLookup })
.done(function(json_data){
var theResponse1 = $.parseJSON(json_data);
myDiscountRate = theResponse1['ourDiscountFound'];
}).then( function(callback){
priceRate = priceRate * (1 - (.01 * myDiscountRate));
newRate = priceRate.toFixed(2);
}
swal({
title: "Confirm",
input: 'checkbox',
inputValue: 0,
type: "warning",
inputPlaceholder: 'I agree to <a href="#blahblahMore"></a> Your new Rate is :'+newRate,
showCancelButton: true,
confirmButtonText: 'Confirm',
showLoaderOnConfirm: true,
preConfirm: function(result) {
return new Promise(function(resolve, reject) { …Run Code Online (Sandbox Code Playgroud) 我想保存一个在Parse云代码中随机生成的registrationId,所以我需要检查该值是否已经在DB中,我必须以递归的方式执行此操作,直到我得到正确的字符串.这是我到目前为止尝试的,问题是findRegistrationId()不是一个承诺所以我不能使用then()有没有办法让它成为一个承诺或任何其他解决方法?对于云代码
function getRandomString()
{
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
var string_length = 4;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum + 1);
}
return randomstring;
}
function findRegistrationId()
{
console.log("Enter findRegistrationId")
var randomString = getRandomString();
var query = new Parse.Query("Book");
query.equalTo("registrationId", randomString);
query.find.then(function(results){
if(results.length === 0)
{
console.log("no registrationId duplicated")
return randomString;
}
//if there is other registrationId we concatenate
else
{
console.log("registrationId duplicated let's recursive it")
return findRegistrationId(); …Run Code Online (Sandbox Code Playgroud) 使用超时实现函数调用
我已经看到许多资源提供Promise.race了在给定时间段内使用超时函数调用的类似示例.这是如何Promise.race在实践中使用的一个很好的例子.这是一些示例代码:
function doWithinInterval(func, timeout) {
var promiseTimeout = new Promise(function (fulfill, reject) {
// Rejects as soon as the timeout kicks in
setTimeout(reject, timeout);
});
var promiseFunc = new Promise(function (fulfill, reject) {
var result = func(); // Function that may take long to finish
// Fulfills when the given function finishes
fulfill(result);
});
return Promise.race([promiseTimeout, promiseFunc]);
}
Run Code Online (Sandbox Code Playgroud)
上面使用的简单方法Promise.race一旦超时func完成就会拒绝承诺.否则,一旦func函数在超时间隔之前完成,项目就会完成.
这听起来不错,易于使用.
但是,这是在Promise中使用超时的最佳做法吗?
当然,如果我们想使用Promises为函数调用设置超时,可以使用上面的方法.这些行动似乎仍然是一个很好的承诺.但是,这被认为是在Promise中使用超时的好方法吗?如果没有,使用它的缺点是什么?
我正在寻找替代方法,但找不到本机的Promise方法来做到这一点.
相反,一些外部Promise库提供timeout如下功能:
蓝鸟供应.timeout() …
我正在尝试编写一个JS代码,如果数据库中已存在给定的数字,它将取消"btn_submit"按钮.onclick事件.我使用AJAX查询给定数字的数据库,并确定是否应该将数据发送到将上传问题的.php站点.为了确定这一点,我需要numOfRows变量的值,但因为我在AJAX中设置它将保持为0. validation()函数将在我的AJAX查询完成之前完成,这会导致问题始终表明给定的数字不是存在于DB中(numOfRows将始终保持为0).在我将validation()函数的结束行中的numOfRows与0进行比较之前,如何等待AJAX查询完成?如果数字中已存在该数字,我需要将false返回到此行:
document.getElementById("btn_submit").onclick = validation;
谢谢!
var textAreaList;
var numOfRows = 0;
var finished = false;
document.getElementById("btn_submit").onclick = validation;
textAreaList = document.getElementsByClassName("text_input");
function validation() {
loadNumRows();
try {
document.getElementById('failure').hidden = true;
}
catch(e) {
console.log(e.message);
}
textAreaList = document.getElementsByClassName("text_input");
var failValidation = false;
for (var i = 0; i < textAreaList.length; i++) {
console.log(textAreaList[i]);
if (textAreaList[i].value == "") {
textAreaList[i].style.border = "2px solid #ff0000";
failValidation = true;
} else {
textAreaList[i].style.border = "2px solid #286C2B";
}
}
return !(failValidation || …Run Code Online (Sandbox Code Playgroud) javascript ×10
promise ×6
ajax ×2
asynchronous ×2
jquery ×2
node.js ×2
automation ×1
bluebird ×1
ecmascript-6 ×1
es6-promise ×1
php ×1
puppeteer ×1
q ×1
sweetalert ×1
sweetalert2 ×1